package com.qys.livesMall.shop.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.shop.mapper.SeckillGoodsMapper;
import com.qys.livesMall.shop.modal.entity.SeckillGoods;
import com.qys.livesMall.shop.modal.query.QuerySeckillGoodsApp;
import com.qys.livesMall.shop.service.SeckillGoodsService;
import com.qys.livesMall.shop.service.ShopGoodsSkuStocksService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gmx
 * @since 2023-07-03
 */
@Service
public class SeckillGoodsServiceImpl extends ServiceImpl<SeckillGoodsMapper, SeckillGoods> implements SeckillGoodsService {
    @Resource
    private SeckillGoodsMapper goodsMapper;
    @Resource
    private ShopGoodsSkuStocksService stocksService;
    @Override
    public Page<SeckillGoods> queryGoods(QuerySeckillGoodsApp data) {
        Page<SeckillGoods> page = Page.of(data.getCurrent(), data.getSize());
        if (ObjectUtils.isEmpty(data.getActivityId())){
            return page;
        }
        page=goodsMapper.queryGoods(page,data);
        if (ObjectUtils.isNotEmpty(data.getShopId())){
            for (SeckillGoods record : page.getRecords()) {
                List<String> attr = new ArrayList<>();
                attr.add(data.getShopId());
                String shopIdAttr = JSONObject.toJSONString(attr);
                record.setShopId(shopIdAttr);
            }
        }
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return page;
        }
        for(SeckillGoods seckillGoods:page.getRecords()){
            if (seckillGoods.getShopId()==null){
                continue;
            }
            List<Long> shopIds= JSONArray.parseArray(seckillGoods.getShopId(),String.class).stream().map(Long::valueOf).collect(Collectors.toList());
            shopIds=stocksService.getShopIdByNum(Long.valueOf(seckillGoods.getSkuId()),shopIds);
            seckillGoods.setShopIds(shopIds);
        }
        return page;
    }

    public List<Long> getShopList(Long skuId){
        List<Long> shopIdList = goodsMapper.getShopId(skuId);
        return shopIdList;
    }

    @Override
    public SeckillGoods getSku(Long skuId, Long activityId) {
        LambdaQueryWrapper<SeckillGoods> wq=new LambdaQueryWrapper<>();
        wq.eq(SeckillGoods::getActivityId,activityId.toString());
        wq.eq(SeckillGoods::getSkuId,skuId.toString());
        wq.last("limit 1");
        return getOne(wq);
    }
}
